<script setup lang="ts">
import { useTagsViewStore } from '@/store/modules/tagsView'
import { computed, watch, ref, toRefs, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import type { TabsPaneContext } from 'element-plus'
import { formatToDateTime } from '@/utils/dateUtil'
import { Screenfull } from '@/components/Screenfull'
import titleBg from '@/assets/bit-screen/titleBg.png'
const router = useRouter()

const { push } = useRouter()

const tagsViewStore = useTagsViewStore()

const getCaches = computed((): string[] => {
  return tagsViewStore.getCachedViews
})

const activeName = ref(null)
const screenFootShow = ref(null)

const handleClick = (tab: TabsPaneContext, event: Event) => {
  const name = toRefs(tab).paneName.value as string
  push({ name })
}

const nowCity = ref('')
const temperature = ref([])
const weatherCondition = ref('')
const getImgUrl = (src) => {
  return new URL(`../../assets/bit-screen/weather/${src}.png`, import.meta.url).href
}
// 获取位置信息
function getLocation() {
  var xhttp = new XMLHttpRequest()
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      var response = JSON.parse(xhttp.responseText)
      nowCity.value = response.city
      fetchWeather(response.latitude, response.longitude)
    }
  }
  xhttp.open('GET', 'https://ipapi.co/json/', true)
  xhttp.send()
}
// 获取天气信息
// function fetchWeather(lat, lon) {
//   const apiKey = '6886fbafdb3d725b113b59e0bee2b41c' // 替换为你的 OpenWeatherMap API Key
//   const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`

//   fetch(url)
//     .then((response) => response.json())
//     .then((data) => {
//       weatherCondition.value = data.weather[0].icon
//       //data.main
//       // Clear 晴； Clouds  多云； Atmosphere：雾霾； Rain：雨； Snow：雪  ；Drizzle：雨夹雪；Thunderstorm：雷雨；
//     })
//     .catch((error) => console.log('Error:', error))

//   const url2 = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`
//   fetch(url2)
//     .then((response) => response.json())
//     .then((data) => {
//       // console.log(data,'最新天气信息'); // 处理返回的数据
//       // 你可以在这里提取和使用天气预报信息
//       temperature.value.push(data.list[0].main.temp_min)
//       temperature.value.push(data.list[0].main.temp_max)
//     })
//     .catch((error) => console.error('Error fetching weather data:', error))
// }
async function fetchWeather(lat: number, lon: number, retries = 5) {  
  const apiKey = '6886fbafdb3d725b113b59e0bee2b41c';  
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`;  
   
  try {  
    const response = await fetch(url);  
    if (!response.ok) throw new Error(`Weather fetch failed: ${response.status}`);  
    const data = await response.json();  

    weatherCondition.value = data.weather[0].icon;  
    // Log or handle your weatherCondition logic here  

    // 第二个请求  
    const url2 = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`;  
    const forecastResponse = await fetch(url2);  
    if (!forecastResponse.ok) throw new Error(`Forecast fetch failed: ${forecastResponse.status}`);  
    const forecastData = await forecastResponse.json();  

    temperature.value.push(forecastData.list[0].main.temp_min);  
    temperature.value.push(forecastData.list[0].main.temp_max);  

  } catch (error) {  
    console.log('Error fetching weather data:', error);  

    if (retries > 0) {  
      console.log(`Retrying... (${5 - retries + 1})`);  
      return fetchWeather(lat, lon, retries - 1);  
    } else {  
      console.error('Failed to fetch weather data after multiple attempts');  
    }  
  }  
}  

getLocation()

// 监听当前路由
watch(
  () => router.currentRoute.value,
  (route: any) => {
    activeName.value = route.name
    screenFootShow.value = route.meta.screenFootShow
  },
  { immediate: true }
)
// 时刻表
const nowTime = ref('')

let timer: number = 0

onMounted(() => {
  timer = window.setInterval(() => {
    nowTime.value = formatToDateTime(new Date())
  }, 1000)
})
onBeforeUnmount(() => {
  clearInterval(timer) //清除定时器
  timer = 0
})
</script>

<template>
  <div class="home-box">
    <!-- 头 S -->
    <div class="hd-box">
      <div class="hd-wrap">
        <img class="title" :src="titleBg" alt="" />
      </div>
      <div class="hd_lf_con">
        <div class="weather">
          <span class="weather-condition mr-10px">
            {{ nowCity || '--' }}
          </span>

          <img
            v-if="weatherCondition"
            class="w-28px h-23px"
            :src="getImgUrl(weatherCondition)"
            alt=""
          />
          <span class="ml-10px" v-if="temperature.length !== 0">
            {{ temperature[0] + '～' + temperature[1] + '℃' }}
          </span>
        </div>
      </div>
      <div class="hd_rt_con">
        <div class="time-table">{{ nowTime }}</div>
        <Screenfull class="screenfull" />
      </div>
    </div>
    <!-- 头 E -->
    <!-- 内容 S -->
    <router-view>
      <template #default="{ Component, route }">
        <keep-alive :include="getCaches">
          <component :is="Component" :key="route.fullPath" />
        </keep-alive>
      </template>
    </router-view>
    <!-- 内容 E -->
    <!-- 尾 S -->
    <div class="ft-box" v-if="screenFootShow">
      <div class="tabs-menu-warp">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- <el-tab-pane label="调度管理" name="bit-screen_control">调度管理</el-tab-pane> -->
          <el-tab-pane name="bit-screen_home">
            <template #label>
              <div
                class="custom-tabs-label"
                style="display: flex; align-items: center; justify-content: space-around"
              >
                <img
                  style="width: 23px; height: 25px; margin-right: 10px"
                  src="@/assets/bit-screen/tab_left.png"
                  alt=""
                />
                <span>机场概况</span>
              </div>
            </template>
          </el-tab-pane>
          <el-tab-pane label="实时监控" name="bit-screen_monitor">
            <template #label>
              <div
                class="custom-tabs-label"
                style="display: flex; align-items: center; justify-content: space-around"
              >
                <img
                  style="width: 21px; height: 21px; margin-right: 10px"
                  src="@/assets/bit-screen/tab_right.png"
                  alt=""
                />
                <span>实时监控</span>
              </div>
            </template>

            <!-- 实时监控 -->
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 尾 E-->
  </div>
</template>
<style>
.gradient-text {
  font-weight: bold;
  background: -webkit-linear-gradient(#fff 50%, #0b87fc 100%);
  background: linear-gradient(#fff 50%, #0b87fc 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;

  /* 兼容非WebKit浏览器 */
}
</style>
<style lang="less" scoped>
.ft-box {
  :deep(.el-tabs__item) {
    width: 150px !important;
    color: #c1d5ff !important;
    font-size: 18px !important;
    padding-right: 0 !important;
  }
  :deep(.el-tabs__item.is-active) {
    width: 150px !important;
    background: url('@/assets/bit-screen/xuanzhong.png') no-repeat;
    background-position: 0 12px;
    // color: #38A9F2 !important;
    text-shadow: 0px 3px 0px rgba(9, 41, 70, 0.66) !important;
  }
  :deep(.el-tabs__nav-scroll) {
    display: inline-flex !important;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
  }
  :deep(.el-tabs__active-bar) {
    display: none;
  }
}

.demo-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}

.home-box {
  position: relative;
  width: 100%;
  height: 100vh;
  background:
    url('@/assets/bit-screen/lf-bg.png') no-repeat left top/15px 100%,
    url('@/assets/bit-screen/rt-bg.png') no-repeat right top/15px 100%,
    url('@/assets/bit-screen/screen-bg.png') no-repeat center/100% 100%;
  color: #fff;

  .sidebar-lf {
    position: absolute;
    left: 5px;
    width: 5px;
    height: 100vh;
  }

  .sidebar-rt {
    position: absolute;
    right: 5px;
    width: 5px;
    height: 100vh;
  }

  // 头
  .hd-box {
    position: relative;
    height: 90px;
    background: url('@/assets/bit-screen/hd-bg.png') no-repeat center top;
    background-size: cover;

    .hd-wrap {
      .title {
        position: relative;
        top: 20px;
        height: 100%;
        width: 400px;
        margin: 0 auto;
      }

      .title-bg {
        width: 800px;
        position: absolute;
        left: 50%;
        top: 30px;
        margin-left: -400px;
      }
    }
    .hd_lf_con {
      position: absolute;
      top: 25px;
      left: 20px;
      .weather {
        background: #11446a;
        font-size: 16px;
        height: 40px;
        line-height: 40px;
        min-width: 160px;
        padding: 0 15px;
        border: 1px solid #38aaf2;
        display: flex;
        align-items: center;
      }
    }

    .hd_rt_con {
      position: absolute;
      top: 25px;
      right: 20px;
      display: flex;
      align-items: center;
      .time-table {
        background: #11446a;
        font-size: 16px;
        height: 40px;
        line-height: 40px;
        min-width: 180px;
        padding: 0 15px;
        border: 1px solid #38aaf2;
      }
      .screenfull {
        margin-left: 15px;
      }
    }
  }

  // 底部
  .ft-box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 80px;
    background: url('@/assets/bit-screen/ft-bg.png') no-repeat center bottom;
    background-size: cover;
    z-index: 10;
    // border: 1px solid;
    .tabs-menu-warp {
      display: flex;
      width: 600px;
      margin: 15px auto 0;

      .el-tabs {
        width: 100%;

        /deep/ .el-tabs__content {
          display: none;
        }

        /deep/ .el-tabs__header {
          margin: 0;

          .el-tabs__nav-wrap::after {
            display: none;
          }

          .el-tabs__nav {
            width: 100%;

            .el-tabs__item {
              font-size: 16px;
              width: 50%;
              color: #fff;
              height: 60px;
              line-height: 60px;
            }

            .el-tabs__active-bar {
              width: 33.33%;
            }
          }
        }
      }
    }
  }
}
</style>
